#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h> // 原生线程库的头文件

const int threadnum = 5;

using namespace std;

class Task
{
public:
    Task(int num1, int num2)
    :_num1(num1), _num2(num2)
    {}

    ~Task()
    {}

    int Excute()
    {
        return _num1 + _num2;
    }

private:
    int _num1;
    int _num2;
};

class ThreadData
{
public:
    ThreadData(int x, int y, const string& thread_name)
    :t(x, y), _thread_name(thread_name)
    {}

    ~ThreadData()
    {}

    string thread_name()
    { 
        return _thread_name; 
    }

    int Run()
    {
        return t.Excute();
    }

private:
    string _thread_name;
    Task t;
    int tid;
};

class Result
{
public:
    Result(int result, const string& thread_name)
    :_result(result)
    ,_thread_name(thread_name)
    {}

    ~Result()
    {}

    void Print()
    {
        cout << _thread_name << " : " << _result << endl;
    }
private:
    string _thread_name;
    int _result;
};

void* handlerTask(void* arg)
{
    ThreadData* thread = static_cast<ThreadData*>(arg);
    string name = thread->thread_name();
    int result = thread->Run();
    Result* r = new Result(result, name);
    delete thread;
    sleep(2);
    return r;
}

int main()
{
    //1.创建线程池
    vector<pthread_t> threads;
    for (int i = 0; i < threadnum; i++)
    {
        char thread_name[64];
        snprintf(thread_name, 64, "Thread-%2d", i + 1);
        pthread_t tid;
        ThreadData* thread = new ThreadData(10, 20, thread_name);
        pthread_create(&tid, nullptr, handlerTask, thread);
        threads.push_back(tid);
    }
    vector<Result*> result_set;
    void* ret = nullptr;
    for (auto& tid : threads)
    {
        pthread_join(tid, &ret);
        result_set.push_back((Result*)ret);
    }
    for (auto& res : result_set)
    {
        res->Print();
        delete res;
    }
    return 0;
}